package epoch.game.core.distr;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import epoch.game.core.buffer.IBuffer;
import epoch.game.core.distr.call.Call;
import epoch.game.core.distr.call.CallReturn;
import epoch.game.core.distr.config.DConfig;
import epoch.game.core.message.SysMessageIds;
import epoch.game.core.serialize.StreamReader;
import epoch.game.core.serialize.StreamWriter;
import epoch.game.core.server.ISession;

public class NodeChannelUtil {
	private static Logger log = LogManager.getLogger(NodeChannelUtil.class);
	
	public static void sendRegMsg(Node node, ISession session) {
		NodeRegisterMessage regmsg = new NodeRegisterMessage();
		regmsg.setNodeId(node.getId());
		regmsg.setHost(node.getHost());
		regmsg.setPort(node.getPort());
		regmsg.setNodeName(node.getName());
		regmsg.setType(node.getType());
		regmsg.setSecretKey(DConfig.NODE_SECRET_KEY);
		StreamWriter writer = new StreamWriter();
		try {
			regmsg.writeTo(writer);
		} catch (Exception e) {
			log.error("sendRegMsg error", e);
		}
		byte[] calldata = writer.array();
		regmsg.setMsgData(calldata);
		//session.write(regmsg);
		RemoteNode.sendNodeMsg(session, regmsg);
	}
	
	public static void handleRpc(Node node, ISession session, int msgId, IBuffer buffer) {
		if (msgId == SysMessageIds.rpc_call) {
			Call call = new Call();
			try {
				call.readFrom(new StreamReader(buffer));
			} catch (Exception e) {
				log.error("handleRpc error", e);
			}
			node.addCall(call);
		} else if (msgId == SysMessageIds.rpc_return) {
			CallReturn callReturn = new CallReturn();
			try {
				callReturn.readFrom(new StreamReader(buffer));
			} catch (Exception e) {
				log.error("handleRpc error", e);
			}
			node.addCallReturn(callReturn);
		} else if (msgId == SysMessageIds.ping) {
			//log.debug("ping from:"+session);
		}
	}
	
}
